home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 3011 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.7 KB  |  76 lines

  1. Newsgroups: comp.lang.c
  2. Path: news.dcs.warwick.ac.uk!not-for-mail
  3. From: D.C.Molero@dcs.warwick.ac.uk (Daniel Castillo Molero)
  4. Subject: problems with a linked list
  5. X-Nntp-Posting-Host: flat
  6. Message-ID: <1996Jan25.125329.23499@dcs.warwick.ac.uk>
  7. Sender: news@dcs.warwick.ac.uk (Network News)
  8. Organization: Department of Computer Science, Warwick University, England
  9. Date: Thu, 25 Jan 1996 12:53:29 GMT
  10.  
  11.  
  12. Dear c community
  13. I'm having some problems with a small c program which uses pointers
  14. and would like to know if any of you could give me a hand.
  15. The following program is intended to create a linked list
  16. of three integers, inserting each one at the beginning of
  17. the current list, and then print the three integers,
  18. but when I run it I get a segmentation fault.
  19.  
  20.  
  21.  
  22. #include <stdio.h>
  23. #include <stdlib.h>
  24.  
  25. struct side
  26. {
  27.   int a;
  28.   struct side *next;
  29. };
  30.  
  31. struct side *i;
  32. struct side *first_side;
  33. struct side *tmp;
  34.  
  35. /* insert a new element in the list */
  36. void store_side(struct side *i, struct side *first_side) {
  37.   if (first_side == NULL) { first_side = i; first_side->next = NULL; }
  38.   else { i->next = first_side; first_side = i; }
  39. }
  40.  
  41. void main(void) {
  42.  
  43. /* insert first element */
  44. first_side = NULL;
  45. i = malloc(1*sizeof(struct side));
  46. (i->a) = 0;
  47. store_side(i, first_side);
  48.  
  49. /* insert second element */
  50. i = malloc(1*sizeof(struct side));
  51. (i->a) = 1;
  52. store_side(i, first_side);
  53.  
  54. /* insert third elemenet */
  55. i = malloc(1*sizeof(struct side));
  56. (i->a) = 2;
  57. store_side(i, first_side);
  58.  
  59. /* print the three elements */
  60. tmp = first_side;
  61. printf("side: %d \n",tmp->a);
  62. while (tmp->next != NULL) {
  63.   tmp = tmp->next;
  64.   printf("side: %d \n",tmp->a);
  65. }
  66.  
  67. }
  68.  
  69. --------------------------------------------------
  70.  
  71. Any help would be greatly appreciated.
  72. -- 
  73. * Daniel Castillo.  D.C.Molero@dcs.warwick.ac.uk *
  74.  
  75.  
  76.